package com.linxi.handy.service.impl;

import com.alibaba.fastjson.JSON;
import com.linxi.handy.common.Constants;
import com.linxi.handy.entity.User;
import com.linxi.handy.service.CacheService;
import com.linxi.handy.util.FileUtils;
import com.linxi.handy.util.LogUtil;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * 账户缓存服务
 *
 * @author mac
 */
public class UserCacheService implements CacheService<User> {

    public static String userCache;

    static {
        try {
            userCache = FileUtils.readContentFromFile(Constants.USERS);
        } catch (Exception e) {
            LogUtil.log(e.getMessage());
            userCache = "[]";
        }
    }

    @Override
    public List<User> getCacheList() {
        return JSON.parseArray(userCache, User.class);
    }

    @Override
    public String getCacheString() {
        return userCache;
    }

    @Override
    public boolean modifyCache(User user) {
        List<User> userList = getCacheList();
        userList.stream().forEach(item -> {
            if (StringUtils.equals(item.toString(), user.toString())) {
                return;
            }
            if (item.getHost().equals(user.getHost())) {
                item.setUser(user.getUser());
                item.setPassword(String.valueOf(user.getPassword()));
            }
        });
        if (StringUtils.equals(JSON.toJSONString(userList), getCacheString())) {
            return false;
        }
        boolean b = FileUtils.writeContentToFile(Constants.USERS, JSON.toJSONString(userList));
        refreshCache();
        return b;
    }

    @Override
    public boolean selectiveUpdateCache(User user) {
        return isExistObj(user) ? modifyCache(user) : addCache(user);
    }

    @Override
    public boolean addCache(User user) {
        List<User> userList = getCacheList();
        userList.add(user);
        boolean b = FileUtils.writeContentToFile(Constants.USERS, JSON.toJSONString(userList));
        refreshCache();
        return b;
    }

    @Override
    public boolean deleteCache(User user) {
        return false;
    }

    @Override
    public boolean isExistObj(User user) {
        return getCacheList().stream().filter(item -> item.getHost().equals(user.getHost())).findFirst().isPresent();
    }

    @Override
    public void refreshCache() {
        userCache = FileUtils.readContentFromFile(Constants.USERS);
    }
}
